package com.example.demo.service;

import com.example.demo.model.entity.Student;
import com.example.demo.model.request.FrontendRequest;
import com.example.demo.model.request.StudentQueryRequest;
import com.example.demo.model.response.SimilarStudentsResponse;
import com.example.demo.util.ExcelExportUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StudentService {

    // 依赖从PredictionService改为TempService
    private final TempService tempService;
    private static final Logger logger = LoggerFactory.getLogger(StudentService.class);

    // 构造函数注入TempService
    public StudentService(TempService tempService) {
        this.tempService = tempService;
    }

    /**
     * 模块一：查询相似学生（调用TempService）
     */
    public List<Student> getSimilarStudents(StudentQueryRequest request) {
        try {
            FrontendRequest frontendRequest = convertToFrontendRequest(request);
            // 调用TempService替代原PredictionService
            SimilarStudentsResponse response = tempService.getSimilarStudents(frontendRequest);
            return convertToStudentList(response.getData());
        } catch (Exception e) {
            logger.error("调用相似学生API失败，返回空列表: {}", e.getMessage());
            return new ArrayList<>();
        }
    }

    /**
     * 导出相似学生Excel
     */
    public byte[] exportSimilarStudents(StudentQueryRequest request) throws IOException {
        List<Student> students = getSimilarStudents(request);
        return ExcelExportUtil.exportStudentsToExcel(students);
    }

    /**
     * 转换请求参数：StudentQueryRequest -> FrontendRequest（逻辑不变）
     */
    private FrontendRequest convertToFrontendRequest(StudentQueryRequest request) {
        FrontendRequest frontendRequest = new FrontendRequest();
//        frontendRequest.setStudent_id(request.getStudent_id());
//        frontendRequest.setName(request.getName());
        frontendRequest.setGpa(request.getGpa());
        frontendRequest.setCet4(request.getCet4());
        frontendRequest.setMath1(request.getMath1());
        frontendRequest.setMath2(request.getMath2());
        frontendRequest.setEnglish1(request.getEnglish1());
        frontendRequest.setEnglish2(request.getEnglish2());
        frontendRequest.setEnglish3(request.getEnglish3());
        frontendRequest.setEnglish4(request.getEnglish4());
        frontendRequest.setMajor(request.getMajor());
        frontendRequest.setCollege(request.getSavedCollege());
        frontendRequest.setTargetSchool(request.getTargetSchool());
        return frontendRequest;
    }

    /**
     * 转换外部API返回数据为Student实体列表（逻辑不变）
     */
    private List<Student> convertToStudentList(List<Map<String, Object>> dataList) {
        if (dataList == null) {
            return new ArrayList<>();
        }
        return dataList.stream().map(data -> {
            Student student = new Student();
            student.setStudent_id(convertToString(data.get("studentId")));
            student.setName(convertToString(data.get("name")));
            student.setGpa(convertToDouble(data.get("gpa")));
            student.setCet4(convertToInteger(data.get("cet4")));
            student.setMath1(convertToDouble(data.get("math1")));
            student.setMath2(convertToDouble(data.get("math2")));
            student.setEnglish1(convertToDouble(data.get("english1")));
            student.setEnglish2(convertToDouble(data.get("english2")));
            student.setEnglish3(convertToDouble(data.get("english3")));
            student.setEnglish4(convertToDouble(data.get("english4")));
            student.setMajor(convertToString(data.get("major")));
            student.setCollege(convertToString(data.get("college")));
            student.setTargetSchool(convertToString(data.get("targetSchool")));
            return student;
        }).collect(Collectors.toList());
    }

    // 类型转换工具方法（逻辑不变）
    private String convertToString(Object obj) {
        return obj != null ? obj.toString() : null;
    }

    private Double convertToDouble(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Number) return ((Number) obj).doubleValue();
        if (obj instanceof String) {
            try {
                return Double.parseDouble((String) obj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    private Integer convertToInteger(Object obj) {
        if (obj == null) return null;
        if (obj instanceof Number) return ((Number) obj).intValue();
        if (obj instanceof String) {
            try {
                return Integer.parseInt((String) obj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }
}